package com.pactera.integral.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.pactera.integral.common.repository.QueryResult;
import com.pactera.integral.common.repository.ResultMap;
import com.pactera.integral.dao.SummaryScoreDao;
import com.pactera.integral.dao.UserDao;
import com.pactera.integral.entity.User;
import com.pactera.integral.service.WXUserService;
import com.pactera.integral.util.DateUtil;

@Service
public class WXUserServiceImpl implements WXUserService {

	@Autowired
	private UserDao userDao;
	
	@Autowired
	private SummaryScoreDao scoreDao;

	public List<ResultMap<String, Object>> getUserDetail(String staffId) {
		String sqlKey = "wxUserDetail.searchByUserId";
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("staffId", staffId);
		QueryResult<ResultMap<String, Object>> result = userDao.findMapListBySQLKey(sqlKey, parameterMap, null);

		return result.getContent();
	}

	public String updatePhoneNumber(String staffId, String newPhone) {
		User user = userDao.findByStaffId(staffId);
		user.setPhone(newPhone);
		userDao.save(user);
		return "SUCCESS";
	}

	public Boolean updatePassword(HttpServletRequest request) {

		String staffId = request.getParameter("staffId");
		String oldPassword = request.getParameter("oldpwd");
		String newPassword = request.getParameter("newpwd");
		User user = userDao.findByStaffId(staffId);
		if (oldPassword != null && (user.getPassword().equals(oldPassword))) {
			user.setPassword(newPassword);
			userDao.save(user);
			return Boolean.TRUE;
		}else{
			return Boolean.FALSE;
		}
	}
	
	/**
	 * 获取个人排名和积分
	 * 
	 * @param staffId
	 * @param scoreType
	 * @return
	 */
	public List<ResultMap<String, Object>> searchSelfScoreAndRank(String staffId, Integer scoreType) {
		String sqlKey = "rankAndScore.searchByStaffId";
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		String departmentCode = getDepartmentCodebyStaffId(staffId);
		parameterMap.put("departmentCode", departmentCode);
		parameterMap.put("scoreMonths", DateUtil.addMonths(scoreType));
		parameterMap.put("staffId", staffId);
		QueryResult<ResultMap<String, Object>> result = scoreDao.findMapListBySQLKey(sqlKey, parameterMap, null);

		return result.getContent();
	}
	
	private String getDepartmentCodebyStaffId(String staffId) {
		User uesr = userDao.findByStaffId(staffId);
		String departmentCode = uesr.getDepartmentCode().substring(0, 4);
		return departmentCode;
	}
}
